package com.dl.mian.http;


import android.text.TextUtils;


import com.dl.mian.utils.LocalDataBox;

import java.io.IOException;
import java.net.Proxy;
import java.util.concurrent.TimeUnit;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

public class DataHelper {

    private static DataHelper instance;
    private final Retrofit retrofit;
    String offline = "http://180.101.206.221:8059/renren-fast/";//"http://121.41.30.138:8189/renren-fast/";
    String online = "http://180.97.199.197:8060/water/";//"http://180.97.199.197:8059/renren-fast/";
    String BASE_URL =
            online;

    public DataHelper() {

        // 设置 请求的缓存的大小跟位置
        // File cacheFile = new File(HuApplication.getAppContext().getCacheDir(), "cache");
        // Cache cache = new Cache(cacheFile, 1024 * 1024 * 50); //50Mb 缓存的大小
        OkHttpClient client =
                new OkHttpClient.Builder()
                        .addInterceptor(getQueryParameterInterceptor()) // 参数添加
                        .addInterceptor(getHeaderInterceptor())
//                        .addInterceptor(new AddTokenInterceptor())//token
                        .addInterceptor(getHttpLoggingInterceptor()) // 日志,所有的请求响应度看到
                        .addInterceptor(new HttpResponseAESInterceptor()) // 返回解密拦截器
                        // .cache(cache)  //添加缓存
                        .connectTimeout(60l, TimeUnit.SECONDS)
                        .readTimeout(60l, TimeUnit.SECONDS)
                        .writeTimeout(60l, TimeUnit.SECONDS)
                        .proxy(Proxy.NO_PROXY)
                        .build();

        retrofit = initRetrofit(BASE_URL, client);
    }

    public static DataHelper getInstance() {
        synchronized (DataHelper.class) {
            if (instance == null) {
                instance = new DataHelper();
            }
        }
        return instance;
    }

    /**
     * 设置公共参数
     */
    private static Interceptor getQueryParameterInterceptor() {
        Interceptor queryParameterInterceptor =
                new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request originalRequest = chain.request();
                        Request request;
                        HttpUrl modifiedUrl =
                                originalRequest
                                        .url()
                                        .newBuilder()
                                        // Provide your custom parameter here
                                        //                        .addQueryParameter("phoneSystem", "")
                                        //                        .addQueryParameter("phoneModel", "")
                                        .build();
                        request = originalRequest.newBuilder().url(modifiedUrl).build();
                        return chain.proceed(request);
                    }
                };
        return queryParameterInterceptor;
    }

    /**
     * 设置头
     */
    private static Interceptor getHeaderInterceptor() {
        Interceptor headerInterceptor =
                new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request originalRequest = chain.request();
                        Request.Builder requestBuilder =
                                originalRequest
                                        .newBuilder()
                                        // Provide your custom header here
                                        .header("Content-Type", "application/json; charset=utf-8");
                        if (!TextUtils.isEmpty(LocalDataBox.getToken())) {
                            requestBuilder = requestBuilder.header("token", LocalDataBox.getToken());
                        }
                        requestBuilder
//                                        .header("token", LocalDataBox.getToken())
//                                        .header("appVerCode", "" + BuildConfig.VERSION_CODE)
//                                        .header("osType", "ANDROID")
//                                        .header("appVerName", BuildConfig.VERSION_NAME)
//                                        .header("Authorization", TextUtils.isEmpty(LocalDataBox.getToken().getAccess_token())?"":LocalDataBox.getToken().getAccess_token())
////                                        .header("lat", "31.457954")
////                                        .header("long", "120.910034")
//                                        .header("lat", LocalDataBox.getCoordinate().split("//")[0])
//                                        .header("long", LocalDataBox.getCoordinate().split("//")[1])
//                                        .header("platform", "1")//android 1
//                                        .header("version", "" + BuildConfig.VERSION_CODE)
                                .method(originalRequest.method(), originalRequest.body());

                        Request request = requestBuilder.build();
                        return chain.proceed(request);
                    }
                };
        return headerInterceptor;
    }

    /**
     * log拦截器
     */
    private static Interceptor getHttpLoggingInterceptor() {
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        // 可以设置请求过滤的水平,body,basic,headers
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        return httpLoggingInterceptor;
    }

    public Retrofit getRetrofit() {
        return retrofit;
    }

    private Retrofit initRetrofit(String baseUrl, OkHttpClient client) {
        return new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(client)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(MyGsonConverterFactory.create(GsonUtil.gson()))
                .build();
    }
}
